package com.ys.controller.api.business;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.ys.config.MenuId;
import com.ys.entity.business.TpBoutique;
import com.ys.entity.business.TpBoutiqueGoods;
import com.ys.entity.sys.YsCol;
import com.ys.service.business.TpBoutiqueService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * 精品表
 */
@Controller
@RequestMapping("/api/inter/tpBoutique")
public class ApiInterTpBoutiqueController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTpBoutiqueController.class);

    @Autowired
    private CommonApiService<TpBoutique> commonApiService;
    @Autowired
    private TpBoutiqueService tpBoutiqueService;

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TpBoutique setSeachSql(TpBoutique cond){
        cond.setStatus(1);//数据过滤
        //排序
        cond.setOrderby("A.UpdateTime DESC");
        cond = commonApiService.dataAuth(MenuId.TP_Boutique, cond);
        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions("tpBoutique:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
    		@ModelAttribute TpBoutique cond){
        try {
            cond = setSeachSql(cond);
            LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
            return tableVoJA;
        }catch (Exception e){
            logger.error("查询精品表出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }


    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(String conditions){
        try {

            //查询条件
            String code = ConditionUtil.getConditionValue(conditions, "code");//商品编码
            String name = ConditionUtil.getConditionValue(conditions, "name");//商品名称
            String codeMerge = ConditionUtil.getConditionValue(conditions, "codeMerge");//合并商品编码
            String boutiqueIsEffect = ConditionUtil.getConditionValue(conditions, "boutiqueIsEffect");//逸思精品生效
            String whereString = "1=1 ";
            if(code!=null && !"".equals(code)){
                whereString += " AND A.Code Like '%"+code+"%' ";
            }
            if(name!=null && !"".equals(name)){
                whereString += " AND A.Name Like '%"+name+"%' ";
            }
            if(codeMerge!=null && !"".equals(codeMerge)){
                whereString += " AND A.CodeMerge Like '%"+codeMerge+"%' ";
            }
            if(boutiqueIsEffect!=null && !"".equals(boutiqueIsEffect)){
                whereString += " AND A.BoutiqueIsEffect = "+Long.parseLong(boutiqueIsEffect);
            }
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .where("A.Code NOT IN ('id','boutiqueId','typeId','aplusId','commodityLmId') ")
                    .where("A.MenuId IN ("+ MenuId.TP_Boutique +","+ MenuId.TP_BoutiqueSiteDetail +") ")
                    .setOrderby("A.MenuId ASC,A.SortNo ASC")
                    .queryList();

            TpBoutique cond = new TpBoutique()
                    //.addField("CASE WHEN A.CountType = 0 THEN '收入' WHEN A.CountType = 1 THEN '支出' ELSE '利润' END countTypeName")
                    //.addField("L.Name AS typeIdTxt")
                    .addField("L.CategoryPath AS baseinfoLmName")

                    .addField("D1.NameUnitCn AS normsUnit")
                    .addField("D2.NameUnitCn AS weightUnit")
                    .addLeftJoin("TP_BoutiqueSiteDetail B ON B.BoutiqueId = A.Id")
                    .addLeftJoin("TB_BaseinfoLmwh L ON B.CommodityLmId = L.Id AND L.Status!=0")
                    .addLeftJoin("TB_BaseinfoDwmc D1 ON B.NormsUnitId = D1.Id AND D1.Status!=0")
                    .addLeftJoin("TB_BaseinfoDwmc D2 ON B.WeightUnitId = D2.Id AND D2.Status!=0")

                    /*
                    .addLeftJoin("TP_AmazonRegionItem I ON B.AmazonRegionItemId = I.Id")
                    .addLeftJoin("TP_AmazonRegion R ON I.RegionCode = R.Code")
                    .addField("I.CountryName AS countryName")//站点
                    .addField("R.Name AS regionName")//区域
                    .addField("R.Platform AS platform")//平台

                     */
                    .addLeftJoin("TB_Site S ON S.Id = B.SiteId")
                    .addLeftJoin("TP_AmazonRegion AR ON AR.Code = S.RegionCode")
                    .addField("AR.Name regionName")
                    .addLeftJoin("TB_Platform B1 ON B1.Code = AR.PlatformCode")
                    //.addField("B1.Code platform")
                    .addField("B1.Name platformName")
                    .addLeftJoin("TB_Country C ON C.Id = S.CountryId")
                    .addField("C.Name countryName")


                    .where(whereString)
                    .setOrderby("A.Code ASC");

            //遍历详情表的字段（字段太多用循环做）
            List<YsCol> listFieldByDetail = listField.stream().filter(item->item.getMenuId().equals(MenuId.TP_BoutiqueSiteDetail)).collect(Collectors.toList());
            for(YsCol item:listFieldByDetail){
                if(!item.getCode().equals("baseinfoLmName")&& !item.getCode().equals("countryName") &&   !item.getCode().equals("regionName")
                        && !item.getCode().equals("platform")  && !item.getCode().equals("normsUnit")  && !item.getCode().equals("weightUnit")
                        && !item.getCode().equals("code")){
                    cond.addField("B."+item.getCode()+" AS "+item.getCode());
                }

            }

            //权限
            cond = commonApiService.dataAuth(MenuId.TP_Boutique, cond);

            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //处理数据
            ExportExcelUtils<TpBoutique> util = new ExportExcelUtils<>(new TpBoutique());
            String toFilePath = util.exportExcel(listData, listField, "精品详情信息表");
            UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出精品表出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }


    /**
     * 修改
     */
    //@RequiresPermissions("tpBoutique:edit")
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            logger.info("精品库修改传参："+params);
            //参数验证
            String errorMsg = tpBoutiqueService.checkParams(params, MenuId.TP_Boutique);
            if(errorMsg!=null && !"".equals(errorMsg)){
                return R.error(errorMsg);
            }
            /*
            //验证精品库站点详情信息是否完善
            //站点列表信息验证
            Long id = Long.parseLong(params.get("id").toString());
            List<Map<String, Object>> hasDetail = new TpBoutiqueSiteDetail().setBoutiqueId(id).queryMap();
            if(hasDetail==null || hasDetail.size()<=0){
                return R.error("至少新增一条站点信息！");
            }
            String errorMsgByDetail = null;
            for(Map<String, Object> item:hasDetail){
                errorMsgByDetail = tpBoutiqueSiteDetailService.checkParams(item,MENU_ID_SITE_DETAIL);
            }
            if(errorMsgByDetail!=null && !"".equals(errorMsgByDetail)){
                return R.error("请将精品库站点详情信息完善再保存！");
            }
             */

            //修改
            return tpBoutiqueService.update(params);
        } catch (Exception e) {
            logger.error("修改精品表出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

	@RequestMapping("/searchForModal")
    @ResponseBody
	public LayuiTableVoJA searchForModal(Model model, HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute TpBoutique cond
			){
		
		return commonApiService.searchLay(cond);
	}


    /**
     * 逸思精品列表数据
     */
    //@RequiresPermissions("tpBoutique:list")
    @RequestMapping("/list")
    @ResponseBody
    public R list(HttpServletRequest request,
    		Integer page, String code,
    		Integer sortType // 排序类型，0或空：按最新更新时间降序，1按销量升序2按销量降序3按价格升序4按价格降序
    		){
        return tpBoutiqueService.list(page, code, sortType);
    }

	/**
	 * 逸思精品设置保存
	 */
	@RequiresPermissions("tpBoutique:setting")
	@PostMapping("/editSetting")
	@ResponseBody
	public R editSetting(HttpServletRequest request,
			@RequestParam Map<String, Object> param){
		return tpBoutiqueService.editSetting(param);
	}

	/**
	 * 逸思精品删除调货信息
	 */
	@PostMapping("/deleteDetail")
	@ResponseBody
	public R deleteDetail(HttpServletRequest request,
			Long id){
		return tpBoutiqueService.deleteDetail(id);
	}

	/**
	 * 逸思精品保存调货信息
	 */
	@PostMapping("/editDetailBatch")
	@ResponseBody
	public R editDetailBatch(HttpServletRequest request,
			Long boutiqueId, String detailArr){
		return tpBoutiqueService.editDetailBatch(boutiqueId, detailArr);
	}


	/**
	 * 逸思精品加入购物车
	 */
	@PostMapping("/addToCart")
	@ResponseBody
	public R addToCart(HttpServletRequest request,
			String choiceShop){
		return tpBoutiqueService.addToCart(choiceShop);
	}

	/**
	 * 逸思精品移出购物车
	 */
	@PostMapping("/removeFromCart")
	@ResponseBody
	public R removeFromCart(HttpServletRequest request,
			Long cartId){
		return tpBoutiqueService.removeFromCart(cartId);
	}



    /**
     * 删除
     */
    @RequestMapping("/delByAuth")
    @ResponseBody
    public R delByAuth(HttpServletRequest request, String ids){
        try {

            JSONArray jsonArray = JSONArray.parseArray(ids);
            if(jsonArray.size()>0){
                for(int i=0;i<jsonArray.size();i++){
                    //删除权限信息
                    tpBoutiqueService.delByAuth(Long.parseLong(jsonArray.get(i).toString()));
                }
            }
            //删除A+信息,根据详情Id
            //tpAplusFileService.delByBoutiqueSiteDetailId(id);
            return R.ok();
        } catch (Exception e) {
            logger.error("删除精品库站点详情信息出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }


	/**
	 * 逸思精品加入购物车
	 */
	@PostMapping("/getPeriodInfo")
	@ResponseBody
	public R getPeriodInfo(Long id){
		
		TpBoutiqueGoods entity = new TpBoutiqueGoods().setId(id).queryFirst();

        String textPeriod = "1、生产货期" + (entity.getPeriod() != null ? entity.getPeriod() : "--") + "天";
        
        String textArriveTime = "2、" + entity.getWarehouse() + "预计到货时间：";
        
    	textArriveTime = textArriveTime + (entity.getTimeArrivePredict() == null || entity.getTimeArrivePredict().length() == 0 ? "--" : entity.getTimeArrivePredict());
		GetPeriodInfoDto dto = new GetPeriodInfoDto(textPeriod, textArriveTime);
		return R.ok(dto);
	}
	@Data
	@AllArgsConstructor
	public static class GetPeriodInfoDto{
		private String textPeriod; // 编码
		private String textArriveTime; // 名称
	}

}